import { Controller, Get, Post, Body, HttpCode, Put, Patch, Delete, Header, Res, Param, Query, HttpStatus } from '@nestjs/common';
import { Response } from 'express';
import * as Joi from '@hapi/joi';
import { validate } from 'src/utils/joi-util';
import { throwValidateException } from 'src/utils/exception-util';
import { getPagerParams } from 'src/utils/request-util';

@Controller('/test')
export class TestController {

  @Get('hello')
  getHello(): string {
    return "hello world";
  }

  @Post('test-post')
  @HttpCode(201)
  async testPost (@Body() body): Promise<any> {
    const schema = Joi.object({
      username: Joi.string().alphanum().min(3).max(30).required(),
      password: Joi.string().pattern(new RegExp('^[a-zA-Z0-9]{3,30}$')),
      repeatPassword: Joi.ref('password'),
      accessToken: [Joi.string(), Joi.number()],
      birthYear: Joi.number().integer().min(1900).max(2013),
      email: Joi.string().email({ minDomainSegments: 2, tlds: { allow: ['com', 'net'] } })
    });
    const validateBody = validate(schema, body);
    
    if (validateBody.username != 'linlifeng') {
      throwValidateException([{
        field: 'username',
        message: 'username not right',
        code: 'username_not_allow'
      }]);
    }

    return validateBody;
  }

  @Put('test-put')
  @HttpCode(201)
  async testPut (@Body() body): Promise<any> {
    return body;
  }


  @Patch('test-patch')
  @HttpCode(201)
  async testPatch (@Body() body): Promise<any> {
    return body;
  }

  @Delete('test-delete')
  async testDelete (): Promise<any> {
    return {
      success: true
    };
  }

  @Delete('test-delete2')
  @HttpCode(HttpStatus.NO_CONTENT)
  async testDelete2 (): Promise<any> {
  }

  @Get('test-pager')
  async testPager (@Query('pager') pagerStr: string): Promise<any> {
    console.log(pagerStr);
    const pagerParams = getPagerParams(pagerStr);
    console.log(pagerParams);
    return pagerParams;
  }

}
